<template>
  <div>
    <slot>
      <p>{{ showTimeFormat }}</p>
    </slot>
  </div>
</template>
<script>
const EMIT_FINISH = 'finish'
const EMIT_CHANGE = 'change'
const TIME_INTERVAL = 1000
</script>
<script setup>
import {
  ref,
  reactive,
  toRefs,
  onMounted,
  watch,
  onUnmounted,
  computed
} from 'vue'
import dayjs from './utils'
const emits = defineEmits([EMIT_FINISH, EMIT_CHANGE])
const props = defineProps({
  // 倒计时的时长
  time: {
    type: [String, Number],
    required: true
  },
  // 倒计时的格式
  format: {
    type: String,
    default: 'HH:mm:ss'
  }
})
const interval = ref(null)
const duration = ref(0)
onUnmounted(() => {
  countFinished()
})
// 倒计时开始
const startCount = () => {
  if (interval.value) {
    clearInterval(interval.value)
  }
  interval.value = setInterval(() => {
    countExecution()
  }, TIME_INTERVAL)
}

// 倒计时执行
const countExecution = () => {
  duration.value -= TIME_INTERVAL
  emits(EMIT_CHANGE)
  if (duration.value <= 0) {
    countFinished()
    return
  }
}
// 倒计时结束
const countFinished = () => {
  if (interval.value) {
    clearInterval(interval.value)
  }
  emits(EMIT_FINISH)
}

watch(
  () => props.time,
  (value) => {
    duration.value = Number(value)
    startCount()
  },
  { immediate: true }
)

// 处理时间格式化并展示
const showTimeFormat = computed(() => {
  return dayjs(duration.value).format(props.format)
})
</script>
<style scoped lang="scss"></style>
